package com.dragonlance.net;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;

public class PackageOut {
	private static final short HEAD = 0x71ab;
	private int length = 0;
	private IoBuffer buff;
	private int code;
	private int extend1 = 0;
	private int extend2 = 0;
	public PackageOut(int code){
		this.buff = IoBuffer.allocate(32);
		this.buff.setAutoExpand(true);
		this.code = code;
		writeHead();
	}

	public PackageOut(int code,int extend1){
		this.buff = IoBuffer.allocate(32);
		this.buff.setAutoExpand(true);
		this.code = code;
		this.extend1 = extend1;
		writeHead();
	}
	
	public PackageOut(int code,int extend1,int extend2){
		this.buff = IoBuffer.allocate(32);
		this.buff.setAutoExpand(true);
		this.code = code;
		this.extend1 = extend1;
		this.extend2 = extend2;
		writeHead();
	}
	
	private void writeHead() {
		writeShort(HEAD);
		writeInt(length);//length
		writeInt(code);
		writeInt(extend1);
		writeInt(extend2);
	}
	
	public void writeInt(int value){
		length += 4;
		this.buff.putInt(value);
	}
	
	public void writeUnsigned(int value){
		length += 1;
		this.buff.putUnsigned(value);
	}
	
	public void writeShort(short value){
		length += 2;
		this.buff.putShort(value);
	}
	
	public void writeUtf(String value) throws CharacterCodingException{
		byte[] bytes = value.getBytes(Charset.forName("UTF-8"));
		this.buff.putShort((short) (bytes.length));
		this.buff.put(bytes);
		length += 2+bytes.length;
	}
	
	public void writeBoolean(boolean value)
	{
		byte b = (byte) (value?1:0);
		this.buff.put(b);
		length += 1;
	}
	
	public void writeFloat(float value)
	{
		this.buff.putFloat(value);
		length+=4;
	}
	
	public void writeDouble(double value)
	{
		this.buff.putDouble(value);
		length+=8;
	}
	
	//打包
	public void pack(){
		this.buff.putInt(2, length);
	}
	
	public IoBuffer getBuff(){
		IoBuffer result = IoBuffer.allocate(32);
		result.setAutoExpand(true);
		buff.flip();
		for(int i=0;i<length;i++){
			result.put(buff.get());
		}
		result.flip();
		return result;
	}
}
